package com.vdongchina.thread.Lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义同步组件来实现独占锁
 * 独占锁的原理
 */
public class Mutex implements Lock {


    private final Sync sync = new Sync();

    @Override
    public void lock() {
        sync.acquire(1);
    }


    //可中断获取锁
    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    //尝试获取锁, 不成功则返回false
    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    //可过期尝试获取锁
    @Override
    public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
        //超时限制,规定时间内没有获取锁则返回false
        return sync.tryAcquireNanos(1, unit.toNanos(timeout));
    }

   //解锁
    @Override
    public void unlock() {
        sync.release(1);
    }

    //获取等待通知组件
    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }

    //内部final申明的方法,不可被复写
    public boolean isLocked(){return sync.isHeldExclusively();}

    //内部final申明的方法,不可被复写
    public boolean hasQueuedThreads(){return sync.hasQueuedThreads();}

    /**
     * AbstractQueuedSynchronizer 队列同步器,锁的核心模板
     * 重新实现,就是复写模板方法
     */
    private static class Sync extends AbstractQueuedSynchronizer {


        //当前同步器是否在独占模式下被线程占用,一般该方法表示是否被当前线程所独占
        @Override
        protected boolean isHeldExclusively() {
            //getState()获取当前同步状态
            return getState() == 1;
        }

        //tryAcquire(int arg) 独占式获取同步锁,如果当前线程获取同步状态成功,由该方法返回,否则进入同步队列等待,该方法会调用重写的tryAcquire(int arg)方法
        //当状态为0时获取锁
        @Override
        protected boolean tryAcquire(int arg) {
            //compareAndSetState(int expect,int update) 使用CAS设置当前状态
            if (compareAndSetState(0, 1)) {
                //设置占用排它锁的线程是当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        //独占锁的释放同步状态,等待获取同步状态的线程将有机会获取同步状态
        //释放锁,将状态设置为0
        @Override
        protected boolean tryRelease(int arg) {
            if (getState() == 0) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        //获取等待通知组件,该组件和当前锁绑定,当前线程只有获取了锁,才能调用该组件的wait(),调用后,当前线程会释放锁
        //返回一个condition,每个condition都包含了一个Condition队列
        Condition newCondition() {
            return new ConditionObject();
        }
    }


}
